<template>
  <div>
    <div class="dsb-pagePanel" ref="devPage">
      <a-row>
        <a-col :span="12">
          <!-- 操作按钮区域 -->
          <div class="table-operator">
            <a-button @click="onAddClick" type="primary" icon="plus" v-has="'user:deviceAdd'">新增</a-button>
            <a-button @click="onExportXlsClick('设备')" type="primary" icon="download"
              v-has="'user:deviceAdd'">导出全部</a-button>
            <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader"
              :action="importExcelUrl" @change="handleImportExcel">
              <a-button type="primary" icon="import" v-has="'user:deviceAdd'">导入</a-button>
            </a-upload>
            <a-dropdown>
              <a-menu slot="overlay">
                <a-menu-item key="1" @click="onAllSelectClick" v-if="bAllSelected"><a-icon type="appstore" />
                  反选</a-menu-item>
                <a-menu-item key="2" @click="onAllSelectClick" v-else><a-icon type="appstore" /> 全选</a-menu-item>
                <a-menu-item key="3" @click="onBatchDelClick"><a-icon type="delete" />删除</a-menu-item>
              </a-menu>
              <a-button style="margin-left: 8px" v-has="'user:deviceAdd'"> 批量操作 <a-icon type="down" /></a-button>
            </a-dropdown>
          </div>
        </a-col>
        <a-col :span="4">
          <a-input-search @change="onSearch" v-model="searchStr" style="width: 95%;" placeholder="请输入设备名称" />
        </a-col>
        <a-col :span="4">
          <a-select ref="select" v-model="deviceStatus" style="width: 95%" @change="handleSelectChange">
            <a-select-option value="全部">全部设备状态</a-select-option>
            <a-select-option value="在线">在线设备</a-select-option>
            <a-select-option value="离线">离线设备</a-select-option>
            <a-select-option value="预警">预警设备</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="1">
          <a-spin style="height:100%;margin-left: 10px;" v-if="loading" />
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" style="margin-top:10px;">
          <!-- <a-row v-for="(row, rowIndex) in productsChunks" :key="rowIndex"> -->
          <ul v-if="showList">
            <div v-for="(item, index) in data">
              <a-col :span="24 / listQuery.colCount" v-bind:key="index + '_#device'" v-show="item.isShow">
                <div class="dsb-deviceCard">
                  <!-- <div @click="selected(item)"> -->
                  <div>
                    <a-row>
                      <a-col :span="1">
                        <a-checkbox v-model="bCheckArr[index]"></a-checkbox>
                      </a-col>
                      <a-col :span="15">
                        <div>
                          <div class="dsb-deviceName">
                            <span>{{ item.name.slice(0, 25) }}</span>
                          </div>
                        </div>
                      </a-col>
                      <a-col :span="8" class="dsb-operation">
                        <div class="title">
                          <span v-if="item.onStatus == 1" class="dsb-statusLight dsb-on">
                            在线
                          </span>
                          <span v-if="item.onStatus == 0" class="dsb-statusLight dsb-off">
                            离线
                          </span>
                          <i class="action-jeecg actionshezhi dsb-statusIcon dsb-on" @click="onSettingClick(item)" />
                          <a-popconfirm title="确定删除吗?" style="color: rgb(224, 118, 118);"
                            @confirm="() => onDeleteClick(item.id)">
                            <i v-has="'user:deviceEdit'" class="action-jeecg actiondelete dsb-deleteIcon" />
                          </a-popconfirm>
                        </div>
                      </a-col>
                    </a-row>
                    <a-row>
                      <a-col :span="12">
                        <a-row>
                          <img src="~@/assets/annuoxing/power_pic.jpg" class="dsb-imgWrap">
                        </a-row>
                        <a-row>
                          <a-col span:="8">
                            <div class="dsb-alarmStatus">
                              <span
                                :class="item.shadowName.warning.mainVol == 0 ? 'dsb-nav-icon-normal dsb-on' : 'dsb-nav-icon-normal dsb-err'">主</span>
                              <span
                                :class="item.shadowName.warning.backVol == 0 ? 'dsb-nav-icon-normal dsb-on' : 'dsb-nav-icon-normal dsb-err'">备</span>
                              <span
                                :class="item.shadowName.warning.temp == 0 ? 'dsb-nav-icon-normal dsb-on' : 'dsb-nav-icon-normal dsb-err'">温</span>
                              <span
                                :class="item.shadowName.warning.current == 0 ? 'dsb-nav-icon-normal dsb-on' : 'dsb-nav-icon-normal dsb-err'">电</span>
                              <span
                                :class="item.shadowName.warning.ups == 0 ? 'dsb-nav-icon-normal dsb-on' : 'dsb-nav-icon-normal dsb-err'">ups</span>
                              <span
                                :class="item.shadowName.warning.cityVol == 0 ? 'dsb-nav-icon-normal dsb-on' : 'dsb-nav-icon-normal dsb-err'">市</span>
                              <span
                                :class="item.shadowName.warning.switches == 0 ? 'dsb-nav-icon-normal dsb-on' : 'dsb-nav-icon-normal dsb-err'">通</span>
                            </div>
                          </a-col>
                        </a-row>
                      </a-col>
                      <a-col :span="12">
                        <div class="dsb-deviceDesc">
                          <span class="dsb-descsSpan">总电流：{{ item.shadowName.baseinfo.supplyCurrent * 10 / 10 }}A</span>
                          <span class="dsb-descsSpan">主电压：{{ item.shadowName.baseinfo.mainVol * 10 / 10 }}V</span>
                          <span class="dsb-descsSpan">备电压：{{ item.shadowName.baseinfo.backVol * 10 / 10 }}V</span>
                          <span class="dsb-descsSpan">温度：{{ item.shadowName.baseinfo.temp * 10 / 10 }}℃</span>
                        </div>
                      </a-col>
                    </a-row>
                    <!-- <a-row>
                      <span style="font-size: 10px;">{{ item.shadowName.warning }}</span>
                    </a-row> -->
                  </div>
                </div>
              </a-col>
            </div>
          </ul>
          <!-- </a-row> -->
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" class="dsb-pagination">
          <MyPagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
            @pagination="loadData"></MyPagination>
        </a-col>
      </a-row>
    </div>
    <tig-device-modal ref="modalForm" @ok="modalFormOk"></tig-device-modal>
  </div>
</template>

<script>
import { getDeviceinfoList } from '@/api/deviceApi'
import { deleteAction, downFile } from '@/api/manage'
import MyPagination from '@/components/tiger/MyPagination'
import TigDeviceModal from './TigDeviceModal'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'


export default {
  name: 'DeviceSelectBox',
  mixins: [JeecgListMixin, mixinDevice],
  props: {
    deviceObj: {
      required: false,
      type: Object,
      default: null,
    },
  },
  components: {
    MyPagination,
    TigDeviceModal
  },
  // computed: {
  //   productsChunks() {
  //     const chunks = [];
  //     for (let i = 0; i < this.total; i += this.listQuery.colCount) {
  //       chunks.push(this.data.slice(i, i + this.listQuery.colCount));
  //     }
  //     return chunks;
  //   },
  // },
  watch: {
    devPageWidth(val) {  //页面适配性配置
      if (val > 800) {
        this.listQuery.colCount = 3
        this.loadData({ orgCode: this.orgCode })
      }
      else if (val <= 800 && val > 350) {
        this.listQuery.colCount = 2
        this.loadData({ orgCode: this.orgCode })
      }
      else {
        this.listQuery.colCount = 1
        this.loadData({ orgCode: this.orgCode })
      }
    },
  },
  data() {
    return {
      showList: true, //是否显示列表 用于刷新列表的
      disableMixinCreated: true,//不执行注入的jeecglistminx的create
      total: 0,
      data: [],
      params: {},
      searchStr: '',
      loading: false,
      selectedId: 0,
      onSelStatus: 0,
      orgCode: '',
      //selStatusDefault: ref('全部'),
      deviceStatus: '全部',
      normalPageSize: 9,
      warningPageSize: 100,
      listQuery: {
        currentPage: 0, //与后台定义好的分页参数
        pageSize: this.normalPageSize,
        colCount: 3,//列显示个数
      },
      bAllSelected: false,
      bCheckArr: [],
      rowCount: 0,
      // 表头
      columns: [
        {
          title: '设备名称',
          align: "center",
          dataIndex: 'name'
        },
        {
          title: '设备IP',
          align: "center",
          dataIndex: 'ipAddr'
        },
        {
          title: '设备端口',
          align: "center",
          dataIndex: 'port'
        },
        {
          title: '所属机构',
          align: "center",
          dataIndex: 'sysOrgCode'
        },
        {
          title: '在线状态',
          align: "center",
          dataIndex: 'onStatus_dictText'
        },
        {
          title: '是否激活',
          align: "center",
          dataIndex: 'ison_dictText'
        },
        {
          title: '所属产品',
          align: "center",
          dataIndex: 'productId',
        }
      ],
      url: {
        list: "/tiger/tigDevice/list",
        delete: "/tiger/tigDevice/delete",
        deleteBatch: "/tiger/tigDevice/deleteBatch",
        exportXlsUrl: "/tiger/tigDevice/exportXls",
        importExcelUrl: "tiger/tigDevice/importExcel",

      },
      superFieldList: [],
      devPageWidth: 0,//页面元素宽度
    }
  },
  created() {
    //this.loadData()
    this.clearSelected()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
  },
  mounted() {
    var that = this;
    //刚进入页面时，获取窗口默认宽高度
    that.windowWidth = document.body.clientWidth

    //进入页面元素默认宽高
    if (that.$refs.devPage != undefined)
      that.devPageWidth = that.$refs.devPage.offsetWidth
    //根据屏幕缩放自动获取页面宽高
    window.onresize = () => {
      return (() => {
        //窗口缩放自动获取元素宽高
        if (that.$refs.devPage != undefined)
          that.devPageWidth = that.$refs.devPage.offsetWidth //宽
      })()
    }
  },
  methods: {
    refreshList() { // 强制刷新列表
      this.showList = false
      this.$nextTick(() => {
        this.showList = true
      })
    },

    initData() {
      for (let item of this.data) {
        let switches = item.shadowName.switches.switches;
        item.shadowName.warning.switches = 0
        item.isShow = true  //设置显示状态
        for (let i = 0; i < item.shadowName.switches.total; i++) {
          let sw = item.shadowName.switches.switches[i];
          if (sw.iswarning) {
            item.shadowName.warning.switches = 1;
            break;
          }
        }
      }

      //导出需要
      let fieldList = [];
      fieldList.push({ type: 'string', value: 'sysOrgCode', text: '所属机构', dictCode: '' })
      fieldList.push({ type: 'string', value: 'name', text: '设备名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'ipAddr', text: '设备IP', dictCode: '' })
      fieldList.push({ type: 'int', value: 'port', text: '设备端口', dictCode: '' })
      fieldList.push({ type: 'int', value: 'onStatus', text: '在线状态', dictCode: 'yn' })
      fieldList.push({ type: 'Text', value: 'shadowName', text: '影子名称', dictCode: '' })
      fieldList.push({ type: 'int', value: 'ison', text: '是否激活', dictCode: 'yn' })
      fieldList.push({ type: 'string', value: 'productId', text: '所属产品', dictCode: "tig_product,name,id" })
      this.superFieldList = fieldList
    },
    clearSelected() {
      this.bAllSelected = false
      for (let i = 0; i < this.listQuery.pageSize; i++) {
        this.bCheckArr[i] = false;
      }
    },

    loadData(_data, _bClearSelected = true) {
      if (_data != null) {
        //接收myPagination回传参数
        if (_data.page != undefined && _data.limit != undefined) {
          this.listQuery.currentPage = _data.page;
          this.listQuery.pageSize = _data.limit;
        }
        if (_data.orgCode != undefined) {
          this.orgCode = _data.orgCode
        }
      }
      //后端页码从下标1开始
      this.params.pageNo = this.listQuery.currentPage + 1;
      this.params.pageSize = this.listQuery.pageSize;
      this.params.sysOrgCode = "*" + this.orgCode + "*";//模糊查询
      if(this.onSelStatus >= 0)
        this.params.onStatus = this.onSelStatus;
      else if(this.onSelStatus == -2){
        this.params.onStatus = 1
      }
      else
        this.params.onStatus = "";
      this.loading = true;
      getDeviceinfoList(this.params).then((res) => {
        if (res.success) {
          this.total = res.result.total;
          this.data = res.result.records;
          this.data.filter(d => {
            d.shadowName = JSON.parse(d.shadowName)
          })
          //console.log("getDeviceinfoList：" + JSON.stringify(this.data))
          this.initData();
          if (_bClearSelected)
            this.clearSelected();
          this.handleSelectChange();
        }
      }).finally(() => {
        this.loading = false
      })
    },



    onSearch() {
      if (this.searchStr != '')
        this.params.name = "*" + this.searchStr + "*";
      else
        delete this.params.name;
      this.listQuery.currentPage = 0;
      this.loadData();
    },
    selected(obj) {
      if (obj.id == this.selectedId) {
        this.$emit('showAgain', obj);
      } else {
        this.selectedId = obj.id;
        this.$emit('update:deviceObj', obj);
      }
    },
    handleSelectChange() {
      if (this.deviceStatus == '全部') {
        // for (let item of this.data) {
        //   item.isShow = true  //设置显示状态
        // }
        if(this.onSelStatus != -1){
          this.onSelStatus = -1
          this.listQuery.pageSize = this.normalPageSize
          this.loadData();
        }
      }
      else if (this.deviceStatus == '在线') {
        if(this.onSelStatus != 1){
          this.onSelStatus = 1
          this.listQuery.pageSize = this.normalPageSize
          this.loadData();
        }
        // for (let item of this.data) {
        //   if (item.onStatus == 1)
        //     item.isShow = true
        //   else
        //     item.isShow = false
        // }
      }
      else if (this.deviceStatus == '离线') {
        if(this.onSelStatus != 0){
          this.onSelStatus = 0
          this.listQuery.pageSize = this.normalPageSize
          this.loadData();
        }
        // for (let item of this.data) {
        //   if (item.onStatus == 0)
        //     item.isShow = true
        //   else
        //     item.isShow = false
        // }
      }
      else if (this.deviceStatus == '预警') {
        if(this.onSelStatus != -2){
          this.onSelStatus = -2
          this.listQuery.pageSize = this.warningPageSize
          this.loadData();
        }
        for (let item of this.data) {
          if (item.shadowName.warning.switches == 1 || item.shadowName.warning.mainVol == 1 || item.shadowName.warning.backVol == 1 ||
            item.shadowName.warning.temp == 1 || item.shadowName.warning.current == 1 || item.shadowName.warning.ups == 1 ||
            item.shadowName.warning.cityVol == 1)
            item.isShow = true
          else
            item.isShow = false
        }
        this.refreshList()
      }
      //this.refreshList()
    },
    /**
     * 设备设置
     */
    onSettingClick(obj) {
      this.$router.push({ path: '/tiger/base/modules/TigDeviceSetting', query: { deviceId: obj.id } })
    },

    onAddClick: function () {
      this.$refs.modalForm.add({ sysOrgCode: this.orgCode });
      this.$refs.modalForm.title = "新增";
      this.$refs.modalForm.disableSubmit = false;
    },

    onDeleteClick: function (id) {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData();
        } else {
          that.$message.warning(res.message);
        }
      });
    },

    onBatchDelClick() {
      var that = this;
      this.$confirm({
        title: "确认删除",
        content: "是否删除选中数据?",
        onOk: function () {
          let ids = "";
          for (let i = 0; i < that.data.length; i++) {
            if (that.bCheckArr[i]) {
              ids += that.data[i].id + ",";
            }
          }
          deleteAction(that.url.deleteBatch, { ids: ids }).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.loadData();
            } else {
              that.$message.warning(res.message);
            }
          });
        }
      });
    },

    onAllSelectClick() {
      for (let i = 0; i < this.listQuery.pageSize; i++) {
        if (!this.bAllSelected)
          this.bCheckArr[i] = true
        else
          this.bCheckArr[i] = false
      }
      this.bAllSelected = !this.bAllSelected;
    },

    onExportXlsClick(fileName) {
      if (!fileName || typeof fileName != "string") {
        fileName = "导出文件"
      }
      let param = this.getQueryParams();
      // if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
      //   param['selections'] = this.selectedRowKeys.join(",")
      // }
      param['selections'] = "";
      for (let item of this.data) {
        param['selections'] += item.id + ",";
      }

      console.log("导出参数", param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },

    modalFormOk() {
      this.loadData();
    },
  },
}
</script>

<style>
.dsb-pagePanel {
  background-color: #fff;
  border-radius: 15px;
  padding-left: 5px;
  height: 100%;
  margin-top: 5px;
  padding-top: 10px;
}

.dsb-deviceItem:hover {
  background-color: #8cc8ff;
  cursor: pointer;
}


.dsb-deviceCard {
  position: relative;
  background-color: #eaeaeaaf;
  font-size: 18px;
  line-height: 18px;
  display: block;
  height: 135px;
  width: 95%;
  padding: 6px 5px;
  margin-bottom: 8px;
  border-radius: 8px;
  cursor: pointer;
}

.dsb-alarmStatus {
  padding-left: 5px;
  margin-top: 5px;
}

.dsb-deviceName {
  padding-left: 8px;
  font-size: 14px;
  font-weight: 600;
  /**超出单行用省略号 */
  /* overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap */
  overflow-wrap: break-word;
  height: 20px;
  /**-------------------------- */
}


.dsb-deviceDesc {
  padding-left: 10px;
  display: flex;
  flex-direction: column;
  font-size: 13px;
  position: absolute;
  right: 15px;
  padding-top: 5px;

  .dsb-descsSpan {
    margin-bottom: 6px;
  }
}

.dsb-pagination {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.dsb-operation {
  display: flex;
  justify-content: center;
  flex-direction: row;
}

.dsb-on {
  color: #0aabf6 !important;
}

.dsb-off {
  color: #b3b4c5 !important;
}

.dsb-err {
  color: red !important;
}

.dsb-statusLight {
  font-size: 13px;
  font-weight: 500;
  vertical-align: top;
  position: absolute;
  left: 0;
}

.dsb-statusIcon {
  font-size: 18px;
  font-weight: 550;
  vertical-align: top;
  position: absolute;
  left: 35px;
}

.dsb-deleteIcon {
  font-size: 16px;
  font-weight: 550;
  vertical-align: top;
  position: absolute;
  right: 0;
  color: rgb(224, 118, 118);
}

/*图标样式*/
.dsb-nav-icon-normal {
  width: 25px;
  height: 18px;
  line-height: 18px;
  display: inline-block;
  border-radius: 2px;
  border-color: #b3b4c5;
  border: 1px solid;
  /* background-color: #b3b4c5; */
  vertical-align: middle;
  overflow: hidden;
  font-size: 8px;
  /* text-indent: 8px; */
  text-align: center;
  /* letter-spacing: 8px; */
  color: #b3b4c5;
  word-break: break-all;
  margin-right: 3px;
}

.deviceSwitchLight {
  vertical-align: auto;
}

.dsb-imgWrap {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 15px;
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}
</style>